package cc.lzmsh.service.impl;

import cc.lzmsh.constants.SystemConstants;
import cc.lzmsh.domain.entity.Article;
import cc.lzmsh.domain.entity.Category;
import cc.lzmsh.domain.vo.CategoryVo;
import cc.lzmsh.mapper.CategoryMapper;
import cc.lzmsh.service.ArticleService;
import cc.lzmsh.service.CategoryService;
import cc.lzmsh.utils.BeanCopyUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 分类表(Category)表服务实现类
 *
 * @author msh
 * @since 2024-09-14 11:31:15
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private ArticleService articleService;

    @Override
    public List<CategoryVo> getCategoryList() {
        QueryWrapper<Article> wrapper = new QueryWrapper<Article>();
        // 查询正常状态的文章
        wrapper.eq("status", SystemConstants.ARTICLE_STATUS_NORMAL);
        // 查询文章列表
        List<Article> articles = articleService.list(wrapper);
        // 获取文章的分类id，并且去重
        Set<Long> categoryIds = articles.stream()
                .map(Article::getCategoryId)
                .collect(Collectors.toSet());
        // 根据文章的分类id查询分类表
        List<Category> categories = listByIds(categoryIds);
        // 查询正常状态的分类
        List<Category> categoryList = categories.stream()
                .filter(category -> SystemConstants.STATUS_NORMAL.equals(category.getStatus()))
                .collect(Collectors.toList());

        return BeanCopyUtils.copyBeanList(categoryList, CategoryVo.class);
    }
}

